package org.custom.spring.boot.security.filters;

import cn.hutool.core.util.ObjectUtil;
import org.custom.spring.boot.security.entity.SystemUserInfo;
import org.custom.spring.boot.security.filters.abstracts.AbstractUnityCommonFilter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 匿名用户认证拦截器
 *
 * @author LiKun
 * @date 2021/11/10 23:33
 */
@Component("anonymousFilter")
public class AnonymousFilter extends AbstractUnityCommonFilter {
    @Override
    protected boolean requestFilterLogicalProcess(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 如果用户未进行认证，则将其认证为 '匿名用户'
        if (ObjectUtil.isNull(authentication) || !authentication.isAuthenticated()) {
            authentication = SystemUserInfo.getAnonymous().getAuthentication();
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        return true;
    }
}
